// client.c
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/socket.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>

#define BUFFER_SIZE 1024

void *receive_message(void *arg) {
    int sockfd = *((int *)arg);
    char buffer[BUFFER_SIZE];
    int bytes_received;

    while ((bytes_received = recv(sockfd, buffer, BUFFER_SIZE - 1, 0)) > 0) {
        buffer[bytes_received] = '\0';
        printf("%s\n", buffer);
    }

    printf("与服务器断开连接。\n");
    pthread_exit(NULL);
}

void show_menu() {
    printf("\n--- 局域网聊天室客户端菜单 ---\n");
    printf("1. 发送消息\n");
    printf("2. 查看在线用户\n");
    printf("3. 退出\n");
    printf("请输入你的选择: ");
}

int main() {
    int client_socket_fd = socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr); // 改为你的服务器IP
    server_addr.sin_port = htons(8080);

    connect(client_socket_fd, (struct sockaddr *)&server_addr, sizeof(server_addr));

    printf("连接成功。\n请输入用户名：");
    char username[BUFFER_SIZE];
    fgets(username, BUFFER_SIZE, stdin);
    username[strcspn(username, "\n")] = '\0';
    send(client_socket_fd, username, strlen(username), 0);

    pthread_t tid;
    pthread_create(&tid, NULL, receive_message, &client_socket_fd);

    int choice;
    char buffer[BUFFER_SIZE];
    while (1) {
        show_menu();
        if (scanf("%d", &choice) != 1) {
            while (getchar() != '\n');
            continue;
        }
        while (getchar() != '\n');

        switch (choice) {
            case 1:
                printf("请输入消息（格式：目标用户名:消息内容）：");
                fgets(buffer, BUFFER_SIZE, stdin);
                buffer[strcspn(buffer, "\n")] = '\0';
                send(client_socket_fd, buffer, strlen(buffer), 0);
                break;
            case 2:
                strcpy(buffer, "GET_ONLINE_USERS");
                send(client_socket_fd, buffer, strlen(buffer), 0);
                break;
            case 3:
                close(client_socket_fd);
                return 0;
        }
    }
    return 0;
}
